package com.jsgt.greekfire.common.widget

import android.content.Context
import android.text.InputType
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.fhx.core.utils.ScreenUtil
import com.jsgt.greekfire.R

class NumberView(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int
) : LinearLayout(context, attrs, defStyleAttr) {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    var valueView: EditText? = null

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberView)
        val valueHint = typedArray.getString(R.styleable.NumberView_hint)
        typedArray.recycle()
        orientation = HORIZONTAL
        gravity = Gravity.CENTER_VERTICAL
        val minusView = initView("-")

        valueView = EditText(context)
        val layoutParams = LayoutParams(
            ScreenUtil.dip2px(context, 122f).toInt(),
            ScreenUtil.dip2px(context, 34f).toInt()
        )
        valueView?.layoutParams = layoutParams
        valueView?.textSize = 12f
        valueView?.gravity = Gravity.CENTER
        valueView?.hint = valueHint
        valueView?.inputType = InputType.TYPE_CLASS_NUMBER
        valueView?.setTextColor(ContextCompat.getColor(context, R.color.gray_848D9A))
        valueView?.setHintTextColor(ContextCompat.getColor(context, R.color.gray_848D9A))
        valueView?.setBackgroundResource(R.drawable.bg_value_number_view)

        val plusView = initView("+")

        plusView.setOnClickListener {
            val value = valueView?.text.toString()
            if (!TextUtils.isEmpty(value)) {
                valueView?.setText("${value.toInt() + 1}")
            }
        }

        minusView.setOnClickListener {
            val value = valueView?.text.toString()
            if (!TextUtils.isEmpty(value) && value.toInt() > 0) {
                valueView?.setText("${value.toInt() - 1}")
            }
        }
        addView(minusView)
        addView(valueView)
        addView(plusView)
    }

    private fun initView(text: String): TextView {
        val layoutParams = LayoutParams(
            ScreenUtil.dip2px(context, 34f).toInt(),
            ScreenUtil.dip2px(context, 34f).toInt()
        )
        val view = TextView(context)
        view.gravity = Gravity.CENTER
        view.layoutParams = layoutParams
        view.text = text
        view.textSize = 18f
        view.setTextColor(ContextCompat.getColor(context, R.color.gray_848D9A))
        view.setBackgroundColor(ContextCompat.getColor(context, R.color.black_212830))
        return view
    }

    fun getText(): String {
        return valueView?.text.toString()
    }
}